Spring IoC容器注入依赖资源主要有以下两种基本实现方式
- 构造器注入
- setter注入
我们在介绍注入之前,先建立一个User实体类,且生成无参、有参构造及setter,重写toString()
方法以便输出信息。
|
|
构造器注入
无参构造
- xml配置
|
|
- test
|
|
- 输出
|
|
结论
xml文件中的配置相当于我们代码中写User user = new User();
。注意
当我们在类中自己生成有参构造时,默认的无参构造要自行添加。
有参构造
- xml配置
|
|
- test
|
|
- 输出
|
|
结论
xml文件中的配置相当于我们代码中写User user = new User("张三","18","zhangsan@qq.com");
。注意
参数的类型和数量必须一致,constructor-arg
标签属性中可以使用index指定参数的位置、使用type指定参数的类型及使用name指定参数的名称。
setter注入
- xml配置
|
|
- test
|
|
- 输出
|
|
- 结论
xml文件中的配置相当于我们代码中写User user = new User(); user.setName("李四")
。
- 注意
setter注入的方法名要遵循“JavaBean getter/setter 方法命名约定”,<property>
标签中name表示类中setter的名字,value表示要注入的参数值。
其他注入测试
我们建下面的一个实体类,我们来测试setter注入boolean,List,Map和Set类型。
注入Boolean类型
- xml配置
|
|
- test
|
|
- 输出
|
|
- 结论
setter注入Boolean类型,<property>
标签中的value值可以是以下几种来代表“真假”
NO. | 支持的参数值 |
---|---|
1 | true/false |
2 | 1/0 |
3 | on/off |
4 | yes/no |
注List类型
- xml文件配置
|
|
- test
|
|
- 输出
|
|
- 结论
注入List需要使用<list>
标签,该标签中有可选的value-type属性,用来指定数据类型,比如value-type=java.lang.String
。
注Map类型
- xml文件配置
|
|
- test
|
|
- 输出
|
|
- 结论
注入List需要使用<map>
标签,该标签中有可选的key-type、value-type属性,用来指定数据类型。
注入Set类型
注入Set需要使用<set>
标签,同注入List一样,该标签中有可选的value-type属性,用来指定数据类型。
p命名空间简化setter注入
- xml文件配置
|
|
- test
|
|
- 输出
|
|
- 结论
p:flag="1"
等价于<property name="flag" value="true"></property>
,可以混合使用哦。